package cn.tom.controller;

import cn.tom.exceptiom.TomException;
import cn.tom.tool.XResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@ControllerAdvice
@Controller
public class ErrController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @ExceptionHandler({TomException.class})
    @ResponseBody
    public void errorHandler2(TomException ex, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf8");
        response.setStatus(501);
        this.log.warn(ex.getMessage());
        try {
            response.getWriter().println(XResp.packJson(501, ex.getMessage(), ""));
            response.flushBuffer();
        } catch (IOException e) {
            this.log.warn(ex.getMessage());
        }
    }
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public void NullException(Exception e, HttpServletResponse response) throws IOException {
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(10001,"空值异常",""));
    }
    @ExceptionHandler(SQLException.class)
    @ResponseBody
    public void SQLException(SQLException e, HttpServletResponse response) throws IOException {
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(10002,"SQL异常",""));
    }

    @ExceptionHandler(IOException.class)
    @ResponseBody
    public void handleIOException(IOException e, HttpServletResponse response) throws IOException {
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(10003, "IO异常", ""));
    }

    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public void handleArrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException e, HttpServletResponse response) throws IOException {
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(10004, "数组越界异常", ""));
    }

}
